package com.ramos.kuaixiao.MyView;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.facebook.drawee.view.SimpleDraweeView;
import com.ramos.kuaixiao.R;
import com.ramos.kuaixiao.utils.SharedPreference;
import com.ramos.kuaixiao.utils.ToastUtils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;


public class SignDialog extends AlertDialog implements View.OnClickListener {

    private Button sure;//确定按钮
    private Button cancel;//取消按钮
    private Activity mContext;//取消按钮
    TextView tv_take_pic;
    TextView tv_address;
    private Uri photoUri;
    public String mImagePath = "";
    SimpleDraweeView sdv_sign_in_picture;
    RelativeLayout rl_take_picture;
    private onNoOnclickListener noOnclickListener;//取消按钮被点击了的监听器
    private onYesOnclickListener yesOnclickListener;//确定按钮被点击了的监听器
    UpdateCarListener updateListener;
    public String mAddress;
    public File mImage;
    /**
     * 初始化界面控件
     */
    private void initView() {
        sure = (Button) findViewById(R.id.btn_submit);
        cancel = (Button) findViewById(R.id.btn_cancel);
        tv_address = (TextView) findViewById(R.id.tv_address);
        tv_address.setText(SharedPreference.getPreferString("descAddress"));
        tv_address.setOnClickListener(this);
        rl_take_picture  = (RelativeLayout) findViewById(R.id.rl_take_picture);
        rl_take_picture.setOnClickListener(this);
        sdv_sign_in_picture = (SimpleDraweeView) findViewById(R.id.sdv_sign_in_picture);
        tv_take_pic = (TextView) findViewById(R.id.tv_take_pic);
    }

    /**
     * 设置取消按钮的显示内容和监听
     *
     * @param onNoOnclickListener
     */
    public void setNoOnclickListener(onNoOnclickListener onNoOnclickListener) {

        this.noOnclickListener = onNoOnclickListener;
    }

    /**
     * 设置确定按钮的显示内容和监听
     *
     * @param onYesOnclickListener
     */
    public void setYesOnclickListener(onYesOnclickListener onYesOnclickListener) {
        this.yesOnclickListener = onYesOnclickListener;
    }

    public SignDialog(Activity context) {
        super(context, R.style.dialogActivityStyle);
        mContext = context;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_sign_in);
        //按空白处不能取消动画
        setCanceledOnTouchOutside(false);
        //初始化界面控件
        initView();
        //初始化界面控件的事件
        initEvent();
    }

    /**
     * 初始化界面的确定和取消监听器
     */
    private void initEvent() {
        //设置确定按钮被点击后，向外界提供监听
        sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (yesOnclickListener != null) {
                    sendErrorAddresss();

                }
            }
        });
        //设置取消按钮被点击后，向外界提供监听
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (noOnclickListener != null) {
                    noOnclickListener.onNoClick();
                }
            }
        });
    }

    private void sendErrorAddresss() {
        mAddress = SharedPreference.getPreferString("descAddress");
        mImage = new File(mImagePath);
        if(mAddress == null || mImage == null){
            ToastUtils.show("图片或地址为空不能提交");
            return;
        } else {
            yesOnclickListener.onYesClick();
        }
        Log.d("sendErrorAddresss", "mAddress:"+ mAddress + " mImage:" + mImage.getAbsolutePath()+ " length "+  mImage.length());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_take_picture:
                takePhoto();
                break;
            case R.id.tv_address:
                tv_address.setText(SharedPreference.getPreferString("descAddress"));
                break;
            default:
                break;
        }
    }

    public void takePhoto() {
        if (Environment.getExternalStorageState().equals("mounted")) {
            String fileDir = mContext.getExternalFilesDir(Environment.DIRECTORY_PICTURES).getAbsolutePath();
            SimpleDateFormat localObject2 = new SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINA);
            File imageFile = new File(fileDir, "/" + localObject2.format(new Date()) + ".jpg");
            try {
                photoUri = Uri.fromFile(imageFile);
                if (photoUri == null) {
                    photoUri = FileProvider.getUriForFile(
                            mContext,
                            "com.ramos.kuaixiao.fileprovider",
                            imageFile);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            Log.d("takePhoto", "takePhoto " + imageFile.getAbsolutePath());
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.putExtra("output", photoUri);
            mImagePath = imageFile.getAbsolutePath();
            Log.d("takePhoto", "mImagePath:" +mImagePath);

            mContext.startActivityForResult(intent, 0xa1);
        } else {
            Toast.makeText(mContext, "内存卡不存在!", Toast.LENGTH_SHORT).show();
        }
    }

    private void showChooseImages(Bitmap originalbitmap) {
        if (originalbitmap != null) {
            savePicture(originalbitmap);
        }
    }

    /**
     * 保存图片到本应用下
     **/
    @SuppressLint("SdCardPath")
    private Bitmap savePicture(Bitmap bitmap) {
        try {
            BufferedOutputStream localBufferedOutputStream = new BufferedOutputStream(
                    new FileOutputStream(new File(mImagePath)));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 10, localBufferedOutputStream);
            localBufferedOutputStream.flush();
            localBufferedOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    public void showImage(){
        Bitmap originalbitmap = BitmapFactory.decodeFile(mImagePath);
        showChooseImages(originalbitmap);
        Glide.with(mContext).load(mImagePath).dontAnimate().centerCrop().diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(sdv_sign_in_picture);
        tv_take_pic.setVisibility(View.GONE);
    }

    /**
     * 设置确定按钮和取消被点击的接口
     */
    public interface onYesOnclickListener {
        void onYesClick();
    }

    public interface onNoOnclickListener {
        void onNoClick();
    }

    public void notifyListeners() {
        updateListener.update();
    }

    public interface UpdateCarListener {
        void update();
    }

    public void setUpdateCarListener(UpdateCarListener updateListener) {
        this.updateListener = updateListener;
    }
}

